<?php
class AuthComponent extends Object {
    var $components = array('Email','Session');
    var $User;
	var $accessDeniedRedirectUrl = '/users/signup';
	var $loginRedirect = '/admin/batches/index';
	var $anonymousAccess = array();
	//called before Controller::beforeFilter()
	function initialize(&$controller, $settings = array()) {
		// saving the controller reference for later use
		$this->controller =& $controller;
        $this->User = ClassRegistry::init('User');
	}

	//called after Controller::beforeFilter()
	function startup(&$controller) {
	   
	}
    
	function checkPermission($permission)
    {
        return (in_array($permission,$this->Session->read('User.permissions')))?true:false;
    }
    
	function check($permission,$message='',$redirect='')
    {
        if($this->checkPermission($permission)) return ;
        if($redirect=='') $redirect = $this->accessDeniedRedirectUrl;
        if($message=='') $message = __('Access Denied',true);
        $this->Session->setFlash($message,true);
        $this->controller->redirect($redirect);
    } 
	
	function checkSession($redirect = '')
	{
		if($this->Session->read('User.email')=='')
		{
			if($redirect=='')
			{
				$redirect = $this->accessDeniedRedirectUrl;
			}		
			$allowedAccess = isset($this->controller->anonymousAccess)?array_merge($this->anonymousAccess,$this->controller->anonymousAccess):$this->anonymousAccess;
			//debug($this->controller->params);
			if(!in_array($this->controller->params['action'],$allowedAccess)){
				$this->Session->write('redirect_url',$this->controller->params['url']);
				$this->controller->redirect($redirect);
			}
		}
	}
	
	function getRedirectUrl()
	{
		if($this->Session->read('redirect_url')!='')
		{
			$this->controller->redirect($this->Session->read('redirect_url'));
			exit(0);
		}
		else
		{
			$this->controller->redirect($this->loginRedirect);
		}
	}
    
}
?>